package com.ui.zhixiao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ui.zhixiao.common.R;
import com.ui.zhixiao.domain.User;
import com.ui.zhixiao.service.UserService;
import com.ui.zhixiao.utils.SMSUtils;
import com.ui.zhixiao.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.nio.channels.Pipe;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();

        if(StringUtils.isNotEmpty(phone)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);


            SMSUtils.sendMessage("戚晨凌的博客","SMS_460950879",phone,code);

            //需要将生成的验证码保存到Session
            session.setAttribute(phone,code);

            return R.success(code);
        }

        return R.error("短信发送失败");
    }

    /**
     * 用户信息分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        Page<User> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(User::getAnswer);
        userService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }


    /**
     * 批量封禁用户
     * @param st
     * @param ids
     * @return
     */
    @PostMapping("/status/{st}")
    public R<String> setStatus(@PathVariable int st,String ids){
        String[] split = ids.split(",");
        List<Long> idList = Arrays.stream(split).map(s->Long.parseLong(s.trim())).collect(Collectors.toList());

        List<User> users = idList.stream().map((item)->{
            User user = new User();
            user.setId(item);
            user.setStatus(st);
            return user;
        }).collect(Collectors.toList());

        userService.updateBatchById(users);
        return R.success("批量操作成功");
    }


}
